package com.community.process._1010.consumer;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.community.process._1010.common.enums.OrderStatusEnum;
import com.community.process._1010.common.utils.RedisConstant;
import com.community.process._1010.common.utils.redis.RedisUtil;
import com.community.process._1010.config.ProcessOrderDelayedQueueConfig;
import com.community.process._1010.dao.entity.ProcessTOrder;
import com.community.process._1010.service.ProcessOrderService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Author: Administrator to Zbs
 * @Date: 2024/7/19 星期五 18:03
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ProcessOrderDelayedQueueConsumer {

    private final ProcessOrderService processOrderService;

    @RabbitListener(queues = ProcessOrderDelayedQueueConfig.QUEUE_NAME)
    public void pwOrderDelayedQueueConfig(String msg, Channel channel, Message message) throws IOException {
        String msg2 = new String(message.getBody(), StandardCharsets.UTF_8);
        log.info("到餐加工-接收订单延迟消息：{}，{}", msg, msg2);
        try {
            // 获取订单信息
            ProcessTOrder tOrder = JSON.parseObject(msg, ProcessTOrder.class);
            // 缓存还存在，表示订单已经超时
            if (StrUtil.isNotBlank(RedisUtil.get(RedisConstant.getProcessOrderRedisKey(tOrder.getTradeNo())))) {
                log.info("到餐加工-订单超时。已处理：{}", msg);
                // 子业务设置超时订单状态，取消订单
                processOrderService.cancelAnOrder(tOrder.getId(), OrderStatusEnum.CANCELLED);
            }
        } catch (Exception e) {
            log.error("到餐加工-订单超时。异常：{}", msg, e);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }
}
